//
//  ULogin.swift
//  swift-cli
//
//  Created by yzd on 2019/5/30.
//  Copyright © 2019 cxw. All rights reserved.
//
import UIKit
import Moya
import HandyJSON
import SVProgressHUD
import Foundation
class UModel : TargetType {
    var baseURL: URL {
        return URL(string: "https://api.ldnkj.com/tire-server")!
    }
    
    var path: String {
        return getPath()
    }
    
    var method: Moya.Method {
        return getMethod()
    }
    
    var sampleData: Data {
        return Data()
    }
    
    var task: Task {
        if let params = self.getParams() {
            if self.method == .post {
                return .requestData(jsonToData(jsonDic: params)!)
            }else {
                return .requestParameters(parameters: params, encoding: URLEncoding.default)
            }
        }
        return .requestPlain
    }
    
    var headers: [String : String]? {
        var header: [String:String] = [:]
        if let token = UserDefaults.standard.string(forKey: String.token) {
            header["token"] = token
        }
        header["Content-Type"] = "application/json;charset=UTF-8"
        return header
    }
    
    func getPath() -> String {
        return "/"
    }
    func getMethod() -> Moya.Method {
        return .post
    }
    func getParams() -> [String : Any]? {
        return nil
    }
    
    private func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? {
        if (!JSONSerialization.isValidJSONObject(jsonDic)) {
            print("is not a valid json object")
            return nil
        }
        let data = try? JSONSerialization.data(withJSONObject: jsonDic, options: [])
        _ = String(data:data!, encoding: String.Encoding.utf8)
        return data
    }
}

struct TestLoginType {
    static let login = "/app/installer/login"
    static let register = "/app/installer/register"
    static let sendCode = "/app/sendSms"
     static let homeSwiper = "/app/installer/serviceAdvertiseList"
}

class TestLogin: UModel {
    var params : [String : Any]?
    var type = TestLoginType.register
    var selfMethod : Moya.Method = .get
    
    convenience init(type: String, params: [String: Any]) {
        self.init(method: .get, type: type, params: params)
    }
//    convenience init(method: Moya.Method, type: String) {
//        self.init(method: .get, type: type, params: nil)
//    }
    
    init(method: Moya.Method, type: String, params: [String: Any]) {
        self.params = params
        self.type = type
        self.selfMethod = method
    }
    
    override func getPath() -> String {
        return self.type
    }
    
    override func getParams() -> [String : Any]? {
        
        return self.params;
    }
    override func getMethod() -> Moya.Method {
        return self.selfMethod
    }
}
